"""
main.py - 交通事件处理平台测试主程序

"""

import time
import logging
from typing import Dict, Any, List, Tuple, Callable
from datetime import datetime
from traffic_platform import EnhancedComprehensiveTrafficPlatform
from result_visualizer import ResultVisualizer
import matplotlib.pyplot as plt
from event_database import event_db

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('traffic_tests.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


class TrafficPlatformTester:
    """交通事件处理平台测试类"""

    def __init__(self):
        """初始化测试环境"""
        self.platform = EnhancedComprehensiveTrafficPlatform()
        self.visualizer = ResultVisualizer()

    def print_result(self, result: Dict[str, Any], verbose: bool = True) -> None:
        """
        打印处理结果

        参数:
            result: 处理结果字典
            verbose: 是否打印详细信息，默认为True
        """
        if not result or result.get("status") != "success":
            logger.error("\n===== 处理失败 =====")
            logger.error(f"错误信息: {result.get('error', '未知错误')}")
            return

        if not verbose:
            logger.info(f"\n事件ID: {result.get('event_id', 'N/A')} - 类型: {result['event_info']['type']}")
            return

        # 结构化输出结果
        output = [
            "\n===== AI处理结果详情 =====",
            f"事件ID: {result.get('event_id', 'N/A')}",
            f"时间: {result.get('timestamp', 'N/A')}",
            "\n位置信息:",
            f" - 经度: {result['location'].get('longitude', 'N/A')}",
            f" - 纬度: {result['location'].get('latitude', 'N/A')}",
            f" - 区域类型: {result['location'].get('area_type', 'N/A')}",
            "\n事件信息:",
            f" - 类型: {result['event_info'].get('type', 'N/A')}",
            f" - 可信度: {result['event_info'].get('confidence', 0):.2f}",
            f" - 严重程度: {result['event_info'].get('severity', 0):.2f}",
            f" - 场景类型: {result['event_info'].get('scene_type', 'N/A')}",
            f" - 人群密度: {result['event_info'].get('crowd_density', 0):.2f}",
            f" - 是否有伤员: {'是' if result['event_info'].get('has_injury', False) else '否'}",
            f"\n警报级别: {result.get('alert_level', 0)}",
            "\n处理方案:"
        ]

        for option in result.get('processing_options', []):
            output.append(f" - {option['name']} (级别: {option['level']}): {option['level_desc']}")

        if result.get('resource_allocation'):
            output.append("\n资源分配:")
            for resource in result['resource_allocation']:
                output.append(f" - {resource}")

        impact = result.get('predicted_impact', {})
        output.extend([
            "\n预计影响:",
            f" - 交通影响指数: {impact.get('traffic_impact', 0):.2f}",
            f" - 预计影响时长: {impact.get('duration', 0)} 分钟"
        ])

        logger.info("\n".join(output))


    def test_case_school_accident(self) -> Dict[str, Any]:
        """测试案例1：学校区域严重事故"""
        device_reports = {
            "device1": {
                "timestamp": int(datetime.now().timestamp()),
                "location": (116.305, 39.905),
                "confidence": 0.92,
                "event_type": "车辆碰撞",
                "severity": 0.9,
                "has_people": True
            },
            "device2": {
                "timestamp": int(datetime.now().timestamp()) + 1,
                "location": (116.306, 39.906),
                "confidence": 0.88,
                "event_type": "车辆碰撞",
                "severity": 0.85,
                "has_people": True
            }
        }
        return self._create_test_case({"device_reports": device_reports})

    def test_case_normal_accident(self) -> Dict[str, Any]:
        """测试案例2：普通区域中等事故"""
        device_reports = {
            "device3": (int(datetime.now().timestamp()), (116.4, 40.0), 0.65, "车辆剐蹭", 0.5, False)
        }
        return self._create_test_case({"device_reports": device_reports})

    def test_case_minor_incident(self) -> Dict[str, Any]:
        """测试案例3：普通区域轻微事件"""
        device_reports = {
            "device4": (int(datetime.now().timestamp()), (116.41, 40.01), 0.45, "车辆急刹", 0.3, False)
        }
        return self._create_test_case({"device_reports": device_reports})

    def performance_test(self, num_runs: int = 10) -> Dict[str, Any]:
        """
        性能测试

        参数:
            num_runs: 测试运行次数，默认为10

        返回:
            包含性能测试结果的字典
        """
        test_cases = [
            ("学校区域严重事故", self.test_case_school_accident),
            ("普通区域中等事故", self.test_case_normal_accident),
            ("普通区域轻微事件", self.test_case_minor_incident)
        ]

        results = {
            'total_time': 0.0,
            'test_cases': {},
            'statistics': {}
        }

        # 预热
        for _, test_func in test_cases:
            test_func()

        # 正式测试
        for case_name, test_func in test_cases:
            case_times = []
            for _ in range(num_runs):
                start_time = time.perf_counter()
                result = test_func()
                elapsed = time.perf_counter() - start_time

                if result.get("status") == "success":
                    case_times.append(elapsed)
                else:
                    logger.warning(f"测试用例 {case_name} 执行失败")

            if case_times:
                results['test_cases'][case_name] = {
                    'times': case_times,
                    'avg_time': sum(case_times) / len(case_times),
                    'min_time': min(case_times),
                    'max_time': max(case_times)
                }
                results['total_time'] += sum(case_times)

        # 计算总体统计信息
        if results['test_cases']:
            all_times = [t for case in results['test_cases'].values() for t in case['times']]
            results['statistics'] = {
                'total_cases': len(all_times),
                'avg_time': sum(all_times) / len(all_times),
                'min_time': min(all_times),
                'max_time': max(all_times)
            }

        return results

    def run_test_suite(self, visualize: bool = True) -> None:
        """
        运行完整测试套件

        """
        logger.info("\n===== 开始交通事件处理平台测试 =====")

        # 功能测试
        test_cases = [
            ("学校区域严重事故", self.test_case_school_accident),
            ("普通区域中等事故", self.test_case_normal_accident),
            ("普通区域轻微事件", self.test_case_minor_incident)
        ]

        for name, test_func in test_cases:
            logger.info(f"\n===== 测试案例: {name} =====")
            result = test_func()
            self.print_result(result)

            if visualize and result.get("status") == "success":
                try:
                    fig = self.visualizer.visualize_result(result)
                    if fig:
                        plt.show()
                        plt.close()
                except Exception as e:
                    logger.error(f"可视化失败: {str(e)}")

        # 性能测试
        logger.info("\n===== 性能测试 =====")
        perf_results = self.performance_test()

        # 打印性能测试结果
        for case_name, data in perf_results['test_cases'].items():
            logger.info(f"\n{case_name}性能:")
            logger.info(f" - 平均时间: {data['avg_time']:.4f}秒")
            logger.info(f" - 最短时间: {data['min_time']:.4f}秒")
            logger.info(f" - 最长时间: {data['max_time']:.4f}秒")

        if perf_results['statistics']:
            stats = perf_results['statistics']
            logger.info("\n===== 总体性能统计 =====")
            logger.info(f"总测试用例数: {stats['total_cases']}")
            logger.info(f"总测试时间: {perf_results['total_time']:.2f}秒")
            logger.info(f"平均处理时间: {stats['avg_time']:.4f}秒")
            logger.info(f"最短处理时间: {stats['min_time']:.4f}秒")
            logger.info(f"最长处理时间: {stats['max_time']:.4f}秒")

        logger.info("\n===== 测试完成 =====")

    def _create_test_case(self, case_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建测试用例并存储到数据库"""
        try:
            # 处理事件
            raw_result = self.platform.process_events(case_data["device_reports"])

            # 存储到数据库
            event_id = event_db.add_event(raw_result)

            # 从数据库获取格式化后的数据
            db_event = event_db.get_event_by_id(event_id)
            formatted_event = event_db.format_event_data(db_event)

            return formatted_event
        except Exception as e:
            logger.error(f"测试用例执行失败: {str(e)}")
            return {"error": str(e), "status": "failed"}

if __name__ == "__main__":
    tester = TrafficPlatformTester()
    tester.run_test_suite()
